<?php
/**
 * @param array $info
 */
function inDatabase($info) {
	global $ddirname;
	$products = $info['product'];
	//vdump($products,false);
	unset($info['product']);
	foreach ($info as $key=>$value) {
		$info[$key] = mysql_real_escape_string($value);
	}
	
	//check whether company exists
	$company_result = DB::result_first("SELECT * FROM company WHERE temp_url='$info[company_index_url]'");
	if(!empty($company_result)){
		$company_exits = true;
	} else {
		$company_exits = false;
	}
	if ($company_exits) {
		$companyExisted = 1;
		$companyUrl = $info['company_index_url'];
		$companyId = DB::result_first("SELECT id FROM company WHERE temp_url='$companyUrl'");
	} else {
		$companyInfo = array(
			'name'=>$info['company_name'],
		);
		$ci = DB::fetch_first("SELECT * FROM company WHERE name='".$info['company_name']."'");
		if (empty($ci)) {
			$companyExisted = 0;
			$companyId = DB::insert('company', $companyInfo, true);
			global $gCompanyNum;$gCompanyNum++;
		} else {
			$companyExisted = 1;
			$companyId = $ci['id'];
		}
	}
	if ($companyId) {
		foreach($products as $product){
			foreach ($product as $key=>$value) {
				$product[$key] = mysql_real_escape_string($value);
			}
			$productInfo = array(
				'name'=>$product['product_name'],
			);
			$pi = DB::fetch_first("SELECT * FROM product WHERE name='".$product['product_name']."' AND companyid=$companyId");
			if (empty($pi)) {
				$productExisted = 0;
				$productId = DB::insert('product', $productInfo, true);
				global $gProductNum;$gProductNum++;
			} else {
				$productId = 0;
				$productExisted = 1;
			}
			if ($productId && $productExisted == 0) {
				$filename = './temp/product_images/'.$ddirname.'/product_'.$productId.'.'.fileExt($product['product_image']);
				if (!file_exists($filename)) {
					ob_start();
					readfile($product['product_image']);
					$img = ob_get_contents();
					ob_end_clean();
					$size = strlen($img);					
					$fp=@fopen($filename, "a");
					fwrite($fp,$img);
					fclose($fp);
				}
				DB::update('product', array('image2'=>$productId.'.'.fileExt($product['product_image'])), "id=$productId");
			}	
		}
	}
	
	if ($companyId && $companyExisted == 0) {
		$filename = './temp/company_logo/'.$ddirname.'/company_'.$companyId.'.'.fileExt($info['company_logo']);
		if (!file_exists($filename)) {
			ob_start();
			readfile($info['company_logo']);
			$img = ob_get_contents();
			ob_end_clean();
			$size = strlen($img);					
			$fp=@fopen($filename, "a");
			fwrite($fp,$img);
			fclose($fp);
		}
		DB::update('company', array('logo2'=>$companyId.'.'.fileExt($info['company_logo'])), "id=$companyId");
	}
}

/**
 *
 */
function vdump($arr,$debug = true){
	echo '<pre>';
	print_r($arr);
	echo '</pre>';
	if($debug)
		exit();

}

/**
 * copy
 * @param string $from
 * @param string $to
 */
function copy_dir($from, $to) {
	if (is_dir($from)) {		
		if (!is_dir($to)) {
			mkdir($to, 0777);
		}
		
		$p = opendir($from);
		while (false !==($file = readdir($p))) {
			if ($file !== '.' && $file !== '..') {
				$tmpFrom = $from.'/'.$file;
				$tmpTo = $to.'/'.$file;
				if (is_dir($tmpFrom)) {
					copy_dir($tmpFrom, $tmpTo);
				} else {
					copy($tmpFrom, $tmpTo);
				}
			}
		}
		closedir($p);
	} else {
		return false;
	}
}

function create_caiji_dir($name,$basedir){
	$p = opendir($basedir);
	while (false !==($file = readdir($p))) {
		if ($file !== '.' && $file !== '..') {
			$dir = $basedir . '/' . $file . '/' . $name;
			if (!is_dir($dir)) {
				mkdir($dir, 0777);
			}
		}
	}
}

/**
 * 
 * @param string $filename
 * @return string
 */
function fileExt($filename) {
	return trim(substr(strrchr($filename, '.'), 1, 10));
}

/**
 * @param $url string
 * @return string
 */
function simulateGet($url) {
	//$url = 'http://www.made-in-china.com/catalog/item999i132/Optical-Fiber-13.html';
	/*$result = file_get_contents($url);*/
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT'] );
	curl_setopt($ch, CURLOPT_TIMEOUT, 100 );
	curl_setopt($ch, CURLOPT_AUTOREFERER, 1 );
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	$result = curl_exec($ch);
	curl_close ($ch);
	//echo $result;die;
	return $result;
}

/**
 * @param string $url
 * @param string $urlfile
 * @return string
 */
function getHtml($url) {
	$hash = md5($url);
	$temp_dir = './temp/'. substr($hash, 10, 2). '/';
	if(!is_dir($temp_dir)){
		mkdir($temp_dir,0777,true);
	}
	$urlfile = $temp_dir . $hash;
	if (file_exists($urlfile)) {
		$fp   = fopen($urlfile,"rb") or die('err');
		$html = '';
		while (!feof($fp)) {
		  $html .= fread($fp, 8192);
		}
		fclose($fp);
	} else {
		sleep(SLEEP_TIME);
		$html = simulateGet($url);
		$fp = fopen($urlfile, 'w') or die("can't open file: " . $urlfile);
		fwrite($fp, $html);
		fclose($fp);
	}
	return $html;
}

/**
 * &nbsp;
 * @param $str
 * @return string
 */
function delSpaces($str) {
	$str = str_replace('&nbsp;', ' ', $str);
	$str = preg_replace('/\s{4,}/', '    ', $str);
	return trim($str);
}

/**
 * &amp;
 * @param $str
 * @return string
 */
function delAmp($str) {
	$str = str_replace('&nbsp;', ' ', $str);
	$str = str_replace('&amp;', '&', $str);
	return trim($str);
}




function cAddslashes($arr) {
	foreach ($arr as $key=>$value) {
		$arr[$key] = addslashes($value);
	}
	return $arr;
}

function strip_br($str){
	$p = array(
		'/\\n/',
		'/\\r/',
	);
	return preg_replace($p, ' ', $str);
}

function array_merge_combine(&$arr1,$arr2){
	if(empty($arr2)){
		return true;
	}
	foreach($arr2 as $k => $v){
		if(isset($arr1[$k])){
			$arr1[] = $v;
		} else {
			$arr1[$k] = $v;
		}
	}
	return true;
}

function preg_match_url($str){
	$url = '';
	if(preg_match('/href=[\"\']([^"]*)[\"\']/', $str, $m)){
		$url = $m[1];
	}
	return $url;
}
